//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { Card, Descriptions, List } from "antd";
import { useDragonFlyStores } from "../store";
import type { TraceInfo } from "@/api/dragonfly/trace";
import { list_trace, SPAN_KIND_CLIENT, SPAN_KIND_CONSUMER, SPAN_KIND_INTERNAL, SPAN_KIND_PRODUCER, SPAN_KIND_SERVER, SPAN_KIND_UNSPECIFIED } from "@/api/dragonfly/trace";
import { get_session } from "@/api/user";
import { gen_access_token } from "@/api/project_server";
import { request } from "@/utils/request";
import moment from "moment";

interface SimpleTraceListProps {
    curTraceId: string;
    onChange: (newTraceId: string) => void;
}

const SimpleTraceList = (props: SimpleTraceListProps) => {
    const appStore = useDragonFlyStores();

    const [traceList, setTraceList] = useState<TraceInfo[]>([]);

    const loadTraceList = async () => {
        if (appStore.traceFilter == null || appStore.traceFilter.filterByTraceId == true || appStore.traceFilter.timeFilter == undefined) {
            return;
        }
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));
        const pasthour = appStore.traceFilter?.timeFilter?.pastHour ?? 1;
        const res = await request(list_trace(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            service: appStore.traceFilter.serviceInfo,
            filter_by_root_span_name: appStore.traceFilter.timeFilter.rootSpanName != "",
            root_span_name: appStore.traceFilter.timeFilter.rootSpanName,
            from_time: moment().subtract(pasthour, "hours").valueOf(),
            to_time: moment().valueOf(),
            limit: 50,
            sort_by: appStore.traceFilter.timeFilter.sortBy,
        }));
        setTraceList(res.trace_list);
    };

    useEffect(() => {
        loadTraceList();
    }, [appStore.traceFilter]);

    return (
        <List rowKey="trace_id" dataSource={traceList} pagination={false} style={{ padding: "10px 10px" }}
            renderItem={traceItem => (
                <List.Item>
                    <Card title={<a style={{ fontSize: "16px" }}
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            props.onChange(traceItem.trace_id);
                        }}>
                        {traceItem.trace_id}
                    </a>} bordered={false} headStyle={{ backgroundColor: props.curTraceId == traceItem.trace_id ? "#ccc" : "#fafafa" }} style={{ width: "100%" }}
                        bodyStyle={{ padding: "0px 0px" }}>
                        <Descriptions column={1} bordered labelStyle={{ width: "90px" }}>
                            <Descriptions.Item label="名称">{traceItem.root_span.span_name}</Descriptions.Item>
                            <Descriptions.Item label="类型">
                                {traceItem.root_span.span_kind == SPAN_KIND_UNSPECIFIED && "未定义"}
                                {traceItem.root_span.span_kind == SPAN_KIND_INTERNAL && "内部服务"}
                                {traceItem.root_span.span_kind == SPAN_KIND_SERVER && "服务端"}
                                {traceItem.root_span.span_kind == SPAN_KIND_CLIENT && "客户端"}
                                {traceItem.root_span.span_kind == SPAN_KIND_PRODUCER && "生产者"}
                                {traceItem.root_span.span_kind == SPAN_KIND_CONSUMER && "消费者"}
                            </Descriptions.Item>
                            <Descriptions.Item label="请求时间">{moment(traceItem.root_span.start_time_stamp).format("YYYY-MM-DD HH:mm:ss")}</Descriptions.Item>
                            <Descriptions.Item label="消耗时间">{traceItem.root_span.end_time_stamp - traceItem.root_span.start_time_stamp}ms</Descriptions.Item>
                        </Descriptions>
                    </Card>
                </List.Item>
            )} />
    );
};

export default observer(SimpleTraceList);